# -*- coding: utf-8 -*-
import json

from django.conf import settings
from django.core.paginator import Paginator
from django.db import transaction
from django.db.models import QuerySet, Q
from django.forms import model_to_dict
from django.http import HttpRequest, JsonResponse, QueryDict
from rest_framework.viewsets import ViewSet

from django_service.messages import failure_response, default_response, message_response
from django_service.models import TableModel, School


def query_one(request: HttpRequest, pk: int, ):
    school: School = School.objects.get(pk=pk)
    school_dict: dict = model_to_dict(school)
    return JsonResponse(school_dict)


def query_any(request: HttpRequest, ):
    query_dict: QueryDict = request.GET
    keywords = query_dict.get('keywords', default='')
    queryset: QuerySet = School.objects.filter(Q(name__startswith=keywords))

    data = [model_to_dict(item) for item in queryset]

    return JsonResponse(message_response(data))


def query_page():
    queryset: QuerySet = School.objects.filter()
    paginator = Paginator(queryset, 10)

    pass


def db_insert(request: HttpRequest):
    if request.content_type != 'application/json':
        return JsonResponse(failure_response(message='ContentType is not application/json'))

    school_dict: dict = json.loads(request.body, encoding=settings.DEFAULT_CHARSET)
    school = School(**school_dict)
    school.save()
    return JsonResponse(default_response())


def db_update(request: HttpRequest):
    return JsonResponse(default_response())


def db_delete(request: HttpRequest):
    return JsonResponse(default_response())


def sync_data(request: HttpRequest):
    prefix = 'school-'
    role_list = list()
    for i in range(10):
        role_list.append(School(name=f'{prefix}{i}'))
        pass

    db_transaction(prefix, role_list)
    return JsonResponse(default_response())


@transaction.atomic
def db_transaction(prefix, role_list):
    # 先delete，再insert
    School.objects.filter(Q(name__startswith=prefix)).delete()
    School.objects.bulk_create(role_list)
    pass


